//
//  EFSWKWebViewController.m
//  LuGong
//
//  Created by zhuangdechao on 2017/7/17.
//  Copyright © 2017年 YiShi. All rights reserved.
//

#import "EFSWKWebViewController.h"
#import "UIViewController+FillNavigationBar.h"
#import "UIColor+YS.h"

static void *WkwebBrowserContext = &WkwebBrowserContext;

@interface EFSWKWebViewController ()<WKNavigationDelegate,WKUIDelegate>
//设置加载进度条
@property (nonatomic,strong) UIProgressView *progressView;
@end


NSString *const kTitle = @"ytx:tTitle"; //title


@implementation EFSWKWebViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupView];
    
    [self initBridge];
    
//    if (self.url) {
//        [self loadPage];
//    }
    if (!self.noSetupFillingViewUnderNavigationBar) {
        [self setupFillingViewUnderNavigationBar];
    }
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //添加进度条
    if (self.isShowProgress) {
        [self.view addSubview:self.progressView];
    }
}


- (void)setupView{

    [self setEdgesForExtendedLayout:UIRectEdgeNone];
    self.webView.translatesAutoresizingMaskIntoConstraints = NO;
    self.webView.backgroundColor = [UIColor lightBackgroundColor];
    self.webView.opaque = NO;
    [self.view addSubview: self.webView];
    NSDictionary *views = @{@"webView": self.webView};
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[webView]|" options:0 metrics:nil views:views]];
    NSString *constraintFormat = self.hasCustomNavigationBar ? [NSString stringWithFormat:@"V:|-%@-[webView]|",@(NavigationAndStatusHeight)] : @"V:|[webView]|";
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:constraintFormat options:0 metrics:nil views:views]];

}


- (void)setUrl:(NSURL *)url
{
    _url = url;
    if ([self isViewLoaded] && !self.isWebViewKeepInMemory) { //不是直播室时
        [self loadPage];
    }
}

- (void)initBridge
{
#ifdef DEBUG
    [WKWebViewJavascriptBridge enableLogging];
#endif
    
    _bridge = [WKWebViewJavascriptBridge bridgeForWebView:_webView];
    [_bridge setWebViewDelegate:self];

    @weakify(self);
    [self.bridge registerHandler:kTitle handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString *title = [data valueForKey:@"type"];
        @strongify(self);
        if (self.getTitleCallback && title.length) {
            self.getTitleCallback(title);
        }
    }];
   
}


- (void)loadPage{
    
    [self.webView stopLoading];
    NSURLRequest *request;
    if (self.cached) {
        request = [NSURLRequest requestWithURL:self.url];
    }
    else {
        request = [NSURLRequest requestWithURL:self.url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
    }
    self.request = request;
    [self.webView loadRequest:request];
}



-(WKWebView *)webView
{
    if (!_webView) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = [WKUserContentController new];
        configuration.allowsInlineMediaPlayback = YES;
        configuration.mediaPlaybackRequiresUserAction = YES;
        
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight) configuration:configuration];
        //kvo 添加进度监控
        [_webView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:WkwebBrowserContext];

    }
    return _webView;
}


- (UIProgressView *)progressView{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
        
        _progressView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 5);
        // 设置进度条的色彩
        [_progressView setTrackTintColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0]];
        _progressView.progressTintColor = [UIColor colorFromHexString:@"#11bc65"];
    }
    return _progressView;
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.webView) {
        [self.progressView setAlpha:1.0f];
        BOOL animated = self.webView.estimatedProgress > self.progressView.progress;
        [self.progressView setProgress:self.webView.estimatedProgress animated:animated];
        
        // Once complete, fade out UIProgressView
        if(self.webView.estimatedProgress >= 1.0f) {
            @weakify(self);
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                @strongify(self);
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                @strongify(self);
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

-(void)dealloc{
    [self.webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
}

@end
